/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.star.admin.controller;

import com.star.common.ActionType;
import com.star.common.CommonUtil;
import com.star.common.RenderModel;
import com.star.common.UserGroupData;
import com.star.common.UserRole;
import com.start.model.ActionModel;
import com.start.model.SessionModel;
import com.start.model.UserGroupModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.File;
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class AdminUserGroupController extends HttpServlet{
    private static final Logger logger = Logger.getLogger(AdminUserGroupController.class);
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminUserGroupController.handle:" + ex.getMessage(), ex);
        }
    }
    
    
    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {  
            case "/ajax-add-group":
                content = ajaxAddGroup(req, resp);
                break;
            case "/ajax-edit-group":
                content = ajaxEditGroup(req, resp);
                break;    
            case "/ajax-delete-group":
                content = ajaxDeleteGroup(req, resp);
                break;
            case "/edit":
                content = renderEditPage(req, resp);
                break;    
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    
    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.USER_GROUP_ADD) && !CommonUtil.checkAccess(req, UserRole.USER_GROUP_EDIT) && !CommonUtil.isAdmin(req)) {
                resp.sendRedirect("/");
                return "";
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, ""));
            dic.setVariable("PAGE_TITLE", "Nhóm người dùng");
            
            if(CommonUtil.checkAccess(req, UserRole.USER_GROUP_ADD) || CommonUtil.isAdmin(req)){
                dic.showSection("ADD_PAGE");
            }
            
            UserGroupModel userGroupModel = UserGroupModel.getInstance();
            List<UserGroupData> userGroupList = userGroupModel.getUserGroup(0, -1);
            for (UserGroupData userGroupData : userGroupList) {
                TemplateDataDictionary section = dic.addSection("LIST_GROUP");
                section.setVariable("GROUP_ID", userGroupData.getId());
                section.setVariable("GROUP_NAME", userGroupData.getGroupName());                
            }

            for (UserRole role : EnumSet.allOf(UserRole.class)) {
                String rid = role.getRole();
                TemplateDataDictionary addSection = dic.addSection("ACCESS_LIST");
                addSection.setVariable("ACCESS_ID", rid);
                addSection.setVariable("ACCESS_NAME", role.getName());

                if (role.isParent()) {
                    addSection.showSection("ACCESS_PARENT");
                } else {
                    addSection.showSection("ACCESS_CHILD");
                }
            }
                                   
            Template template = RenderModel.getAdminCTemplate("group_manage");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminUserGroupController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    private String renderEditPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.USER_GROUP_EDIT) && !CommonUtil.isAdmin(req)) {
                resp.sendRedirect("/usergroup");
                return "";
            }
            
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, ""));
            dic.setVariable("PAGE_TITLE", "Cập nhật nhóm người dùng");
                        
            dic.showSection("EDIT_PAGE");            
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.isEmpty()) {
                resp.sendRedirect("/usergroup");
                return "";
            }       
            
            UserGroupModel userGroupModel = UserGroupModel.getInstance();
            UserGroupData userGroupData = userGroupModel.getUserGroupById(id); 
            if (userGroupData != null) { 
                dic.setVariable("GROUP_ID_EDIT", userGroupData.getId());
                dic.setVariable("GROUP_NAME_EDIT", userGroupData.getGroupName());
                   
                List<String> lstRole = userGroupModel.getGroupRole(id);
                for (UserRole role : EnumSet.allOf(UserRole.class)) {
                    String rid = role.getRole();
                    TemplateDataDictionary addSection = dic.addSection("ACCESS_LIST");
                    addSection.setVariable("ACCESS_ID", rid);
                    addSection.setVariable("ACCESS_NAME", role.getName());

                    if (lstRole != null && lstRole.contains(rid)) {
                        addSection.showSection("ACCESS_GAIN");
                    }
                    if (role.isParent()) {
                        addSection.showSection("ACCESS_PARENT");
                    } else {
                        addSection.showSection("ACCESS_CHILD");
                    }
                }
                                
                List<UserGroupData> userGroupList = userGroupModel.getUserGroup(0, -1);
                for (UserGroupData item : userGroupList) {
                    TemplateDataDictionary section = dic.addSection("LIST_GROUP");
                    section.setVariable("GROUP_ID", item.getId());
                    section.setVariable("GROUP_NAME", item.getGroupName());                
                }   
                                      
                Template template = RenderModel.getAdminCTemplate("group_manage");
                content = template.renderToString(dic);
            } else {
                resp.sendRedirect("/usergroup");
                return "";
            }
        } catch (Exception ex) {
            logger.error("AdminUserGroupController.renderEditPage: " + ex.getMessage(), ex);
        }
        return content;
    }
           
    
    private String ajaxAddGroup(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.USER_GROUP_ADD) && !CommonUtil.isAdmin(req)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Thêm nhóm thành công.";
        Map<String, String> data = new HashMap<>();
        try {
            String groupName = "";                
            String lstRole = "";
                                
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);

            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    switch (name) {
                        case "groupName":
                            groupName = value;
                            break;                            
                        case "childCheck":
                            lstRole += value + ",";
                            break;                            
                    }
                }                     
            }
            
            if (groupName.equalsIgnoreCase("")) {
                msg = "Tên nhóm không được trống.";
                error = -1;
            }
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();                
                String userLogin = sessionModel.getUserLogin(req);
                UserGroupModel userGroupModel = UserGroupModel.getInstance();
                UserGroupData userGroupData = new UserGroupData(groupName, lstRole.equals("") ? lstRole : lstRole.substring(0, lstRole.length() - 1));
                String gId = userGroupModel.addUserGroup(userGroupData);
                if (gId.isEmpty()) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.GROUP_ADD, gId, groupName);
                }
                data.put("id", gId);                                     
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }
    
    
    private String ajaxEditGroup(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.USER_GROUP_EDIT) && !CommonUtil.isAdmin(req)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Cập nhật nhóm người dùng thành công.";
        Map<String, String> data = new HashMap<>();
        try {
            String groupId = "";
            String groupName = "";                
            String lstRole = "";            

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);

            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    switch (name) {
                        case "groupID":
                            groupId = value;
                            break;
                        case "groupName":
                            groupName = value;
                            break;                            
                        case "childCheck":
                            lstRole += value + ",";
                            break;                         
                    }
                }                 
            }
            if (groupName.equalsIgnoreCase("")) {
                msg = "Tên nhóm không được trống.";
                error = -1;
            }
            
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();                
                String userLogin = sessionModel.getUserLogin(req);
                UserGroupModel userGroupModel = UserGroupModel.getInstance();
                UserGroupData userGroupDataEdit = userGroupModel.getUserGroupById(groupId);
                UserGroupData userGroupData = new UserGroupData(groupId, groupName, 
                        lstRole.equals("") ? lstRole : lstRole.substring(0, lstRole.length() - 1));    
                boolean updateGroup = userGroupModel.updateUserGroup(userGroupData);
                if (!updateGroup) {
                    error = -1;
                    msg = "Có lỗi xảy ra.";
                }
                else{             
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.GROUP_EDIT, groupId, userGroupDataEdit.getGroupName());
                }                
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }
    
    
    private String ajaxDeleteGroup(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.USER_GROUP_EDIT) && !CommonUtil.isAdmin(req)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Xóa nhóm người dùng thành công.";
        try {
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.equalsIgnoreCase("")) {
                msg = "Id nhóm không được trống.";
                error = -1;
            }
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);
                UserGroupModel userGroupModel = UserGroupModel.getInstance();
                UserGroupData userGroupData = userGroupModel.getUserGroupById(id);
                
                boolean deleteGroup = userGroupModel.deleteUserGroup(id);
                if (!deleteGroup) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.GROUP_DELETE, id, userGroupData.getGroupName());
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }
}
